<template>
  <view>
    <up-popup :show="popupShow" mode="center" :round="8" :closeOnClickOverlay="false" @open="popupShow = true">
      <view class="alter-mock">
        <view class="row-title">发现新版本&nbsp;V{{newVersion}}</view>
        <view class="row-content">更新内容</view>
        <view class="row-nav">{{content}}</view>
        <view class="btn">
          <up-button type="primary" v-if="!progressShow" text="立即更新" style="background: none" :plain="true"
            color="#237AE4" @click="renew"></up-button>
          <up-line-progress :percentage="percentage" v-else>
            <text class="u-percentage-slot">{{percentage}}%</text>
          </up-line-progress>

        </view>
      </view>
    </up-popup>
  </view>
</template>


<script setup>
  import {
    version
  } from './api.js'
  import {
    ref,
    reactive,
    nextTick
  } from 'vue'
  import {
    onLoad,
  } from '@dcloudio/uni-app';
  const newVersion = ref('')
  const popupShow = ref(false)
  const progressShow = ref(false)
  const percentage = ref(0)
  const content = ref('')
  const data = ref({})
  onLoad(() => {
    nextTick(() => {
      // #ifdef APP-PLUS
      versionApi()
      // #endif
    })
  })
  const versionApi = (async () => {
    const systemInfo = uni.getSystemInfoSync()
    const res = await version({
      type: 1
    })
    if (res && res.code === 1) {
      console.log(res.data, 3334)
      data.value = res.data
      const contrast = compare(res.data.version, systemInfo.appVersion)
      console.log(1111, contrast)
      if (contrast === 1) {
        popupShow.value = true
        newVersion.value = res.data.version
        content.value = res.data.content
        renew()
      } else {
        console.log('当前就是最新版本');
      }
    }

  })
  //整包更新
  function renew() {
    if (uni.getSystemInfoSync().platform === 'ios') {
      let appleId = '6738649500'
      plus.runtime.launchApplication({
          action: `itms-apps://itunes.apple.com/cn/app/id${appleId}?mt=8`
        },
        function(e) {
          console.log('Open system default browser failed: ' + e.message);
        }
      );
    } else {
      this.progressShow = true
      const filelist = uni.downloadFile({
        url: this.data.androidUrl,
        success(res) {
          console.log(res);
          if (res.statusCode === 200) {
            plus.runtime.install(res.tempFilePath, {
              force: true
            }, () => {
              plus.runtime.restart();
            })
          } else {
            const that_ = this
            uni.showModal({
              content: '下载失败,请重试',
              success: function(res) {
                if (res.confirm) {
                  this.renew()
                  console.log('用户点击确定');
                } else if (res.cancel) {
                  console.log('用户点击取消');
                }
              }
            });
            this.progressShow = false
          }
        }
      })
      filelist.onProgressUpdate((res) => {
        this.percentage = res.progress
      });
      plus.runtime.openURL(res.data.androidUrl);
    }

  }
  //热更新
  function updateHot(url) {
    console.log(444, url)
    uni.downloadFile({
      url,
      success: (downloadResult) => {
        console.log(888, downloadResult);
        if (downloadResult.statusCode === 200) {
          // 下载更新文件成功后进行安装
          plus.runtime.install(downloadResult.tempFilePath, {
              force: false // 是否强制安装, 如果将要安装应用的版本号不高于现有应用的版本号则终止安装，并返回安装失败。
            },
            function(res) {
              console.log(999, res);
              uni.showToast({
                title: '更新完毕，即将重启',
                icon: 'none',
                position: 'bottom'
              })
              setTimeout(() => {
                plus.runtime.restart(); // 安装完成后重启应用
              }, 2000)
            })
        }
      }
    });

  }
  //对比版本号
  function compare(version1, version2) {
    console.log(999, version1, version2)
    let arr1 = version1.split(".");
    let arr2 = version2.split(".");
    let length = Math.max(arr1.length, arr2.length);
    for (let i = 0; i < length; i++) {
      const n1 = Number(arr1[i] || 0)
      const n2 = Number(arr2[i] || 0)
      if (n1 > n2) return 1
      if (n1 < n2) return -1
    }
    return 0

  }
</script>
<style lang="less" scoped>
  .wrap {

    position: relative;
    z-index: 999;
  }

  .alter-mock {
    height: 500rpx;
    width: 690rpx;
  }

  .row-title {
    margin-top: 60rpx;
    text-align: center;
    font-size: 36rpx;
    font-weight: 700;

  }

  .row-content {
    margin-top: 30rpx;
    padding: 0 60rpx;
    font-size: 32rpx;
    font-weight: 700;
  }

  .row-nav {
    margin-top: 20rpx;
    padding: 0 60rpx;
    max-height: 160rpx;
    height: 160rpx;
  }


  .btn {
    background-color: #ffffff;
    width: 100%;
    padding: 16rpx 44rpx;
    box-sizing: border-box;
    display: flex;
    justify-content: space-between;

    .u-button {
      height: 80rpx;
      // width: 296rpx;
      border-radius: 10rpx;
      margin: 0;
    }

    .submit-button {
      width: 300rpx;
      border-radius: 10rpx;
    }
  }
</style>